package com.ifcar.app.activity;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.ifcar.app.util.StringUtil;
import com.ifcar.app.util.ThemeSettingsHelper;
import com.ifcar.app.util.Tools;
import com.ifcar.app.activity.R;

public class FeedBackActivity extends BaseActivity{
	
	private EditText edit_feedbackmessage;
	private Button do_feedback_button;
	private String message = "";
	private ProgressDialog proDialog;

	private Message cancelmsg;
	private String headinfo = "";
	private DefaultHttpClient httpclient;
	private TextView feedback_desc;
	private TextView feedback_text_remain;
	private EditText feedback_email;
	private SharedPreferences set_prefs;
	private String account = "";
	
	private InputMethodManager imm;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.feedback);
		
		set_prefs = PreferenceManager.getDefaultSharedPreferences(this);
		account = set_prefs.getString("feedback_account", "");
		if(account.equals("")) account = set_prefs.getString("account", "");
		
		findViewsById();
		setListener();
		
		cancelmsg = new Message();
		cancelmsg.what=2;
		
		headinfo = "["
					+"android"
					+"_"+getResources().getString(R.string.versionnum)
					+"_"+Build.MODEL
					+"_"+Build.VERSION.RELEASE
					+"]";
	}
	
	/** 初始化注册View组件 */
	private void findViewsById() {
		imm = (InputMethodManager) this.getSystemService(INPUT_METHOD_SERVICE);
		
		edit_feedbackmessage = (EditText) findViewById(R.id.edit_feedbackmessage);
		do_feedback_button = (Button) findViewById(R.id.do_feedback_button);
		
		feedback_desc = (TextView) findViewById(R.id.feedback_desc);
		feedback_desc.setText("您的设备是："+android.os.Build.MODEL
				+"，系统版本是："+android.os.Build.VERSION.RELEASE
				+"，使用的网易新闻客户端版本是："+this.getResources().getString(R.string.versionnum));
		feedback_desc.setVisibility(View.GONE);
		feedback_email = (EditText) findViewById(R.id.feedback_email);
		if(!account.equals("")) feedback_email.setText(account);
		
		feedback_text_remain = (TextView)findViewById(R.id.feedback_text_remain);
		feedback_text_remain.setText(Html.fromHtml("还可输入<font color=\"#e80f0f\">" + 500 + "</font>字"));
		
		edit_feedbackmessage.requestFocus();
		imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);  
	}
	
	/** 设置监听器 */
	private void setListener() {
		do_feedback_button.setOnClickListener(feedbackListener);
		
		edit_feedbackmessage.addTextChangedListener(new TextWatcher() {
			private CharSequence temp;				
			private int length = 0;
			
			@Override
			public void afterTextChanged(Editable arg0) {
			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1,
					int arg2, int arg3) {
				// TODO Auto-generated method stub
				temp = arg0;
			}

			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {
				
				length = 500-temp.length();
				feedback_text_remain.setText(Html.fromHtml("还可输入<font color=\"#e80f0f\">" + length + "</font>字"));
				
			}
			
		});
	}
	
	/** 提交Button Listener */
	private OnClickListener feedbackListener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			//do_feedback_button.setEnabled(false);
			message = edit_feedbackmessage.getText().toString();
			
			proDialog = ProgressDialog.show(FeedBackActivity.this, "","正在提交反馈...", true, true);
			proDialog.setCancelable(true);
			proDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
				
				@Override
				public void onCancel(DialogInterface arg0) {
					// TODO Auto-generated method stub
					if(null!=proDialog){
						proDialog.dismiss();
					}
					
				}
			});
			
			set_prefs.edit().putString("feedback_account", feedback_email.getText().toString()).commit();
			
			if(null != message && !"".equals(message.trim())){
				
				if(message.trim().length()>500){
					Toast.makeText(FeedBackActivity.this, "内容请不要超过500字，谢谢！",Toast.LENGTH_SHORT).show();
					if (null != proDialog
							&& proDialog
									.isShowing()) {
						proDialog.dismiss();
					}
				}else{
					message = message.trim() + " （联系邮箱：" + feedback_email.getText().toString() + "）";
					postEditMessage pe = new postEditMessage();
					pe.start();
				}
				
				
				
			}else{
				
				if (null != proDialog
						&& proDialog
								.isShowing()) {
					proDialog.dismiss();
				}
				Toast.makeText(FeedBackActivity.this, "请填写反馈信息，谢谢您的支持！",Toast.LENGTH_SHORT).show();
				
				
				
				do_feedback_button.setEnabled(true);
			
			}
			
		}
	};
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(event.getRepeatCount()>1){
			return super.onKeyDown(keyCode, event);
		}
		do_feedback_button.setEnabled(true);
	   return super.onKeyDown(keyCode, event);		
	}
	
	public void goBackClick(View view){
		finish();
	}
	
	class postEditMessage extends Thread {
		final String a = feedback_email.getText().toString();
		@Override
		public void run() {
			// TODO Auto-generated method stub
			Message msg = new Message();
			msg.what = 1;
			String title = headinfo+message.substring(0, message.length()>10?10:message.length());
			title = title.substring(0, title.length()>35?35:title.length());			
			try{
				HttpPost httpRequest = new HttpPost(StringUtil.FEEDBACKURL);
				
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				params.add(new BasicNameValuePair("boardid", "newsfeedback"));
				params.add(new BasicNameValuePair("title", title));
				params.add(new BasicNameValuePair("comment", message));
				if(a != null && !a.equals("")) {
					params.add(new BasicNameValuePair("email", a));
				}
				httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
				httpclient = new DefaultHttpClient();
				Tools.setHttpClientHostProxy(httpclient, FeedBackActivity.this);
				HttpResponse httpResponse = httpclient.execute(httpRequest);
				
				msg.arg1 = 0;
				
			}catch(Exception ex){
				msg.arg1 = 1;
			}
			
			reflashormoreDataHandler.sendMessage(msg);
		}
	}
	
	Handler reflashormoreDataHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {

			switch (msg.what) {
			
			case 1:// 分享到微博
				
				if(msg.arg1 == 1) {
					if (null != proDialog) {
						proDialog.dismiss();
					}
					Message message = new Message();
					Bundle bundle = new Bundle();
					bundle.putString("errorinfo", "提交反馈失败！");
					message.setData(bundle);
					httpHandler.sendMessage(message);

				} else {
					if (null != proDialog) {
						proDialog.dismiss();
					}
					Toast.makeText(FeedBackActivity.this, "感谢您提供的反馈！",Toast.LENGTH_SHORT).show();
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					FeedBackActivity.this.finish();
				}
				
				break;
			case 2:
				
				break;
			
			}
		}
	};
	
	//异常处理提示
	Handler httpHandler = new Handler() {
		public void handleMessage(Message msg) {
			String errorinfo = msg.getData().getString("errorinfo");
			
				Toast.makeText(FeedBackActivity.this, errorinfo,Toast.LENGTH_SHORT).show();

		}
	};
	
	@Override
    protected void onDestroy() {
        if(null!=proDialog&&proDialog.isShowing()){
            proDialog.dismiss();
        }
        super.onDestroy();
    }
	
	 @Override
	    public void onApplyTheme() {
	        super.onApplyTheme();
	        ThemeSettingsHelper themeSettingsHelper = getThemeSettingsHelper();
	        themeSettingsHelper.setViewBackgroud(this, R.id.whole_space, R.drawable.loginbg);
	        themeSettingsHelper.setViewBackgroud(this, R.id.top_space, R.drawable.top_background);
	        themeSettingsHelper.setTextViewColor(this, R.id.top_main_text, R.color.main_title_color);
	        themeSettingsHelper.setViewBackgroud(this, R.id.do_feedback_button, R.drawable.netease_big_button);
	        themeSettingsHelper.setTextViewColor(this, R.id.do_feedback_button, R.color.list_title_color);
	      //返回夜间模式
	        themeSettingsHelper.setImageViewSrc(this, R.id.top_id_image, R.drawable.go_back);
	    }

}
